package com.szt.sy.config.security.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.szt.sy.anontation.Authority;
import com.szt.sy.anontation.AuthorityConfig;
import com.szt.sy.config.SecurityConfig;
import com.szt.sy.util.security.SecurityUtils;
import com.szt.sy.util.web.AjaxUtils;
import com.szt.sy.vo.rep.base.RepBaseVO;
import com.szt.sy.vo.rep.base.ResultCode;

/****
 * 后台-认证
 * 
 * @author wwy
 *
 */
@Component
public class AdminAuthenticationInterceptor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		HandlerMethod method = (HandlerMethod) handler;
		AuthorityConfig authorityConfig = AnnotationUtils.findAnnotation(method.getBean().getClass(),
				AuthorityConfig.class);
		Authority authority = AnnotationUtils.findAnnotation(method.getMethod(), Authority.class);
		if (authorityConfig == null) {
			return true;
		}
		// 先验证菜单权限
		boolean canAccess = SecurityUtils.hasAuthority(authorityConfig.prefix());
		if (!canAccess) {
			authorityRrror(request, response);
			return false;
		}
		// 验证按钮权限
		canAccess = SecurityUtils.hasAuthority(authorityConfig.prefix(), authority.name());
		if (!canAccess) {
			authorityRrror(request, response);
			return false;
		}
		// 保存权限前缀
		request.setAttribute(SecurityConfig.AUTHORITY_PREFIX_ATTRIBUTE_NAME, authorityConfig.prefix());
		return true;
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}
	
	private void authorityRrror(HttpServletRequest request, HttpServletResponse response) {
		if (AjaxUtils.isAjaxRequest(request) || AjaxUtils.isAjaxUploadRequest(request)) {
			response.setContentType("application/json;charset=UTF-8");
			RepBaseVO<String> repVO = new RepBaseVO<>();
			repVO.setCode(ResultCode.AUTHORITY_ERROR).setMes(ResultCode.AUTHORITY_ERROR.getMes());
			try {
				response.getWriter().print(JSON.toJSONString(repVO));
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				response.sendError(403);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
